#!/bin/bash -e
#
# Control step motor rotate of sled

# shellcheck source=meta-facebook/meta-bletchley/recipes-bletchley/plat-tools/files/bletchley-common-functions
source /usr/libexec/bletchley-common-functions

#######################################
# Setting step motor control pins to start/stop motor
# Arguments:
#   1. SLED NUMBER
#   2. Value of STBY RESET PIN
#   3. Value of ENABLE PIN
#   4. Value of DIRECTION PIN
#   5. Value of Motor Driver VREF PIN
#######################################
function set_motor() {
    local sled_gpio_num
    sled_gpio_num=$(sled_mapping "$1")
    STBY_PIN="SLED${sled_gpio_num}_MD_STBY_RESET"
    EN_PIN="SLED${sled_gpio_num}_MD_IOEXP_EN_FAULT"
    DIR_PIN="SLED${sled_gpio_num}_MD_DIR"
    VREF_PIN="SLED${sled_gpio_num}_MD_REF_PWM"
    set_gpio "$STBY_PIN" "$2"
    set_gpio "$EN_PIN"   "$3"
    set_gpio "$DIR_PIN"  "$4"
    set_gpio "$VREF_PIN" "$5"
}

function show_usage(){
    echo "Usage: motor-ctrl [$SLED_LIST]  [f r s]"
    echo "      f : Step Motor go forward"
    echo "      r : Step Motor go reverse"
    echo "      s : Step Motor stop "
}

if [ $# -ne 2 ]; then
    show_usage
    exit 1;
fi

if is_sled_valid "$1"; then
    SLED=$1
    SLED_NUM=${SLED:4}
    ACTION=$2
else
     echo "invalid sled name: $1"
    exit 1;
fi

#Check if sled is present
if ! is_sled_present "${SLED_NUM}"; then
    echo "${SLED} is not present!"
    exit 1
fi

if [[ "$ACTION" == "s" ]]; then
    echo "stop motor"
    set_motor "$SLED_NUM" 1 0 0 1
elif [[ "$ACTION" == "f" ]];then
    echo "start motor, direction:forward"
    set_motor "$SLED_NUM" 1 1 0 0
elif [[ "$ACTION" == "r" ]];then
    echo "start motor, direction:reverse"
    set_motor "$SLED_NUM" 1 1 1 0
else
    echo "Error: Unknown action!"
    exit 1
fi

exit 0

